﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GN.Pay.Core.Entities;
using GN.Pay.Core.Values;
using System.Security.Cryptography;
using GN.Pay.Utils.Security;

namespace GN.Pay.Core.Runtime.Impl
{
    /// <summary>
    /// App 安全
    /// </summary>
    public class AppSecurity : IAppSecurity
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        private void Info(MerchantAppInfo app, out string key, out string iv)
        {
            key = app.MerchantId.Substring(4, 8);
            iv = app.Id.Substring(6, 8);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public AppSecurityInfo Encrypt(MerchantAppInfo app)
        {
            using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider(1024))
            {
                string key;
                string iv;
                Info(app, out key, out iv);
                return new AppSecurityInfo(DesUtils.Encrypt(provider.ToXmlString(true), key, iv),
                    DesUtils.Encrypt(provider.ToXmlString(false), key, iv),
                    DesUtils.Encrypt(Guid.NewGuid().ToString("N").ToUpper(), key, iv),
                    DesUtils.Encrypt(Guid.NewGuid().ToString("N").ToUpper(), key, iv));
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public AppSecurityInfo Decrypt(MerchantAppInfo app)
        {
            string key;
            string iv;
            Info(app, out key, out iv);
            return new AppSecurityInfo(DesUtils.Decrypt(app.PrivateKey, key, iv),
                DesUtils.Decrypt(app.PublicKey, key, iv),
                DesUtils.Decrypt(app.SignKey, key, iv),
                DesUtils.Decrypt(app.AppKey, key, iv));
        }
    }
}
